package com.example.docking.service.impl;

import com.example.docking.dao.jindie.ResponseData;
import com.example.docking.dao.jindie.response.TokenData;
import com.example.docking.service.BaseService;
import com.example.docking.service.KingdeeApiService;
import com.example.docking.util.Constants;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.smecloud.apigw.constant.HttpMethod;
import com.smecloud.apigw.model.ApiRequest;
import com.smecloud.apigw.model.ApiResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.TimeUnit;

public class BaseServiceImpl implements BaseService {
    private static final Logger log = LoggerFactory.getLogger(BaseServiceImpl.class);
    // 使用 ConcurrentHashMap 模拟缓存，同时记录每个缓存项的过期时间
    private static final ConcurrentHashMap<String, CacheEntry> tokenCache = new ConcurrentHashMap<>();
    // 定义缓存项的过期时间为 60 分钟，可根据实际情况调整
    private static final long EXPIRE_TIME = TimeUnit.MINUTES.toMillis(30);
    Map<String, String> map = new HashMap<>();

    String apptoken;

    {
        try {
            apptoken = getAppToken();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 内部类，用于存储缓存项的值和过期时间戳
    private static class CacheEntry {
        private final String value;
        private final long expirationTime;

        public CacheEntry(String value, long expirationTime) {
            this.value = value;
            this.expirationTime = expirationTime;
        }

        public String getValue() {
            return value;
        }

        public boolean isExpired() {
            return System.currentTimeMillis() > expirationTime;
        }
    }

    @Override
    public String getAppToken() throws Exception {
        // 先从缓存中获取 token
        CacheEntry cacheEntry = tokenCache.get("appToken");
        if (cacheEntry != null && !cacheEntry.isExpired()) {
            log.info("从缓存中获取到 appToken");
            return cacheEntry.getValue();
        }

        KingdeeApiService kingdeeApiService = new KingdeeApiServiceImpl();
        ApiResult apiResult = kingdeeApiService.xApiSignature();
        Gson gson = new Gson();
        Type type = new TypeToken<ResponseData<TokenData>>() {
        }.getType();
        ResponseData<TokenData> response = gson.fromJson(apiResult.getBody(), type);

        // 将以下的 System.out.println 替换为日志记录
        log.info("金蝶Code: {}", response.getErrcode());
        log.info("金蝶Message: {}", response.getDescription());
        log.info("金蝶data: {}", response.getData().getApp_token());

        // 获取到新的 token 后，放入缓存
        String newToken = response.getData().getApp_token();
        long expirationTime = System.currentTimeMillis() + EXPIRE_TIME;
        tokenCache.put("appToken", new CacheEntry(newToken, expirationTime));
        log.info("金蝶将新的 appToken 放入缓存");

        return newToken;
    }

    protected ApiResult sendApiRequestGet(String path, Map<String, String> map, Object object) throws Exception {
        KingdeeApiService kingdeeApiService = new KingdeeApiServiceImpl();
        ApiRequest request = new ApiRequest(HttpMethod.GET, Constants.HOST, path);
        request.addHeader("app-token", apptoken);
        request.addHeader("X-GW-Router-Addr", Constants.X_GW_Router_Addr);
        request.setQuerys(map);
        // 创建 Gson 对象
        Gson gson = new Gson();
        request.setBodyJson(gson.toJson(object).getBytes(StandardCharsets.UTF_8));
        return kingdeeApiService.apigwClient().send(request);
    }

    protected ApiResult sendApiRequestPostBody(String path, Map<String, String> map, Object object) throws Exception {
        KingdeeApiService kingdeeApiService = new KingdeeApiServiceImpl();
        ApiRequest request = new ApiRequest(HttpMethod.POST_BODY, Constants.HOST, path);
        request.addHeader("app-token", apptoken);
        request.addHeader("X-GW-Router-Addr", Constants.X_GW_Router_Addr);
        request.setQuerys(map);
        Gson gson = new Gson();
        request.setBodyJson(gson.toJson(object).getBytes(StandardCharsets.UTF_8));

        // 将以下的 System.out.println 替换为日志记录
        log.info("保存金蝶的请求body内容为:{}", gson.toJson(object));
        log.info("保存金蝶的请求body内容为:{}", new String(request.getBody(), StandardCharsets.UTF_8));

        return kingdeeApiService.apigwClient().send(request);
    }
}